package tool

import (
	"github.com/golang-jwt/jwt/v5"
	"github.com/spf13/viper"
)

type JWTClaim struct {
	Id string
	jwt.RegisteredClaims
}

func GenerateJWT(info map[string]string) string {
	claims := &JWTClaim{
		Id:               info["id"],
		RegisteredClaims: jwt.RegisteredClaims{Subject: "TOKEN"},
	}
	secretKey := viper.GetString("jwt.secret-key")
	token, _ := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(secretKey))
	return token
}

func ParseJWT(tokenContent string) (*JWTClaim, error) {
	secretKey := viper.GetString("jwt.secret-key")
	token, err := jwt.ParseWithClaims(tokenContent, &JWTClaim{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(secretKey), nil
	})
	if err != nil {
		return nil, err
	}
	claims, ok := token.Claims.(*JWTClaim)
	if !ok {
		return nil, err
	}
	return claims, nil
}
